package com.house365.arequest;


import com.house365.arequest.convert.ResponseConvert;
import com.house365.arequest.listener.OnExceptionListener;

import java.lang.ref.SoftReference;
import java.util.HashMap;

import io.reactivex.plugins.RxJavaPlugins;
import retrofit2.Retrofit;

/**
 * @author Arvin
 */
public class ARequest {
    private static boolean DEBUG = BuildConfig.DEBUG;


    private static OnExceptionListener onExceptionListener;
    /**
     * 缓存请求service,不会重复创建
     */
    private static HashMap<Class, SoftReference> map = new HashMap<>();

    /**
     * http返回码为200时的json解析接口
     * 用于处理服务器返回的错误状态
     * 详见该接口
     */
    private static ResponseConvert convert;

    private static Retrofit retrofit;

    /**
     * 获取请求service实例
     *
     * @param service
     * @param <T>
     * @return
     */
    public static <T> T create(final Class<T> service) {
        T t = null;
        SoftReference softReference = map.get(service);
        if (softReference != null) {
            t = (T) softReference.get();
        }
        if (t == null) {
            t = retrofit.create(service);
            map.put(service, new SoftReference(t));
        }
        return t;
    }


    /**
     * 使用懒汉的单例模式, 需要传入初始化完成的retrofit
     *
     * @param retrofit
     */
    private synchronized static void setRetrofit(Retrofit retrofit) {
        if (ARequest.retrofit == null) {
            ARequest.retrofit = retrofit;
        }
    }


    public static ResponseConvert getConvert() {
        return convert;
    }


    public static final class Builder {
        public Builder setRetrofit(Retrofit retrofit) {
            ARequest.setRetrofit(retrofit);
            return this;
        }

        public Builder setResponseConvert(ResponseConvert convert) {
            ARequest.convert = convert;
            return this;
        }

        public Builder setOnExceptionListener(OnExceptionListener onExceptionListener) {
            ARequest.onExceptionListener = onExceptionListener;
            return this;
        }

        public void build() {
            /**
             * 全局的rxjava报错拦截器，如果你实现了onError，则不会走到这里
             */
            RxJavaPlugins.setErrorHandler(throwable -> {
                if (DEBUG) {//Debug时，直接抛出异常
                    throw new Exception(throwable);
                } else {//非debug时，会捕获异常，此时你需要收集改bug，而不是忽略
                    if (onExceptionListener != null) {
                        onExceptionListener.onException(throwable);
                    }

                }
            });
        }
    }

}
